package com.von.nhcf.mvc.controller;

import com.von.nhcf.entity.Auth;
import com.von.nhcf.entity.Role;
import com.von.nhcf.service.AdminService;
import com.von.nhcf.service.AuthService;
import com.von.nhcf.service.RoleService;
import com.von.nhcf.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * 权限分配控制器，控制各种权限的分配
 * @author
 */
@Controller
public class AssignController {
    @Autowired
    AdminService adminService;
    @Autowired
    RoleService roleService;
    @Autowired
    AuthService authService;

    @RequestMapping("assign/do/auth.json")
    @ResponseBody
    public ResultEntity doAssignAuth(@RequestBody Map<String, List<Integer>> requestBody) {
        authService.doAssignAuth(requestBody);
        return ResultEntity.successWithoutData();
    }
    @RequestMapping("assign/get/assigned.json")
    @ResponseBody
    public ResultEntity doGetAssigned(@RequestParam("roleId") Integer roleId) {
        List<Integer> authByRoleid = authService.getAssignedAuthByRoleid(roleId);
        return ResultEntity.successWithData(authByRoleid);
    }
    @RequestMapping("assign/get/auth.json")
    @ResponseBody
    public ResultEntity doGetAllAuth() {
        List<Auth> auths = authService.getAll();
        return ResultEntity.successWithData(auths);
    }
    @RequestMapping("assign/do/admin/assigning.html")
    public String doAdminAssignRole(@RequestParam("adminId")Integer adminId, @RequestParam("pageNum") Integer pageNum,
                               @RequestParam("keyword") String keyword, @RequestParam(value = "roleIdList", required = false) List<Integer> roleIdList) {
        roleService.doAdminAssignRole(adminId, roleIdList);

        return "redirect:/assign/to/page.html?adminId="+adminId+"&pageNum="+pageNum+"&keyword="+keyword;
    }

    @RequestMapping("assign/to/page.html")
    public String toAssignRolePage(@RequestParam("adminId") Integer adminId, ModelMap modelMap) {
        // 查询已分配角色
        List<Role> assignedRoleList = roleService.getAssignedRole(adminId);
        // 查询未分配角色
        List<Role> unAssignedRoleList = roleService.getUnAssignedRole(adminId);
        // 存入模型
        modelMap.addAttribute("assignedRoleList", assignedRoleList);
        modelMap.addAttribute("unAssignedRoleList", unAssignedRoleList);

        return "assign_page";
    }
}
